<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>云盘系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#375659',
                        secondary: '#AAC6C2',
                        accent: '#6D8B74',
                        neutral: '#F4F4F2',
                    },
                    fontFamily: {
                        sans: ['Arial', 'sans-serif'],
                        yahei: ['"Microsoft YaHei"', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .transition-custom {
                transition: all 0.3s ease;
            }
            .bg-gradient-custom {
                background: linear-gradient(135deg, #AAC6C2 0%, #8AA8A1 100%);
            }
            .card-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            }
            .btn-hover-effect {
                transition: all 0.3s ease;
            }
            .btn-hover-effect:hover {
                background-color: #375659;
                color: white;
            }
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="bg-neutral min-h-screen font-yahei bg-cover bg-center" style="background-image: url('pic1.png');">
<!-- 页面容器 -->
<div class="max-w-6xl mx-auto px-4 py-8">
    <!-- 标题区域 -->
    <header class="text-center mb-12">
        <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-primary mb-2">云盘系统</h1>
    </header>

    <!-- 主内容区域 -->
    <main class="flex flex-col md:flex-row gap-8">
        <!-- 左侧面板 - 登录/注册 -->
        <div class="w-full md:w-1/3">
            <div class="bg-white rounded-xl p-6 card-shadow">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-xl font-semibold text-primary">用户操作</h2>
                </div>

                <!-- 登录表单 -->
                <div id="loginSection" class="mb-8">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">登录</h3>
                    <form id="loginForm" class="space-y-4">
                        <div class="form-group">
                            <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                            <input type="text" id="username" name="username" required
                                   class="block w-full rounded-lg border border-gray-300 py-2 px-4 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
                        </div>
                        <div class="form-group">
                            <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="password" name="password" required
                                   class="block w-full rounded-lg border border-gray-300 py-2 px-4 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
                        </div>
                        <button type="submit"
                                class="w-full bg-white text-primary border-2 border-primary rounded-lg py-2 px-4 font-medium btn-hover-effect">
                            登录
                        </button>
                    </form>
                </div>

                <!-- 注册表单 -->
                <div id="registerSection">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">注册</h3>
                    <form id="registerForm" class="space-y-4">
                        <div class="form-group">
                            <label for="newUsername" class="block text-sm font-medium text-gray-700 mb-1">新用户名</label>
                            <input type="text" id="newUsername" name="newUsername" required
                                   class="block w-full rounded-lg border border-gray-300 py-2 px-4 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
                        </div>
                        <div class="form-group">
                            <label for="newPassword" class="block text-sm font-medium text-gray-700 mb-1">新密码</label>
                            <input type="password" id="newPassword" name="newPassword" required
                                   class="block w-full rounded-lg border border-gray-300 py-2 px-4 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
                        </div>
                        <button type="submit"
                                class="w-full bg-white text-primary border-2 border-primary rounded-lg py-2 px-4 font-medium btn-hover-effect">
                            注册
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- 右侧面板 - 文件操作 -->
        <div class="w-full md:w-2/3">
            <div id="fileOperations" class="bg-white rounded-xl p-6 card-shadow hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-xl font-semibold text-primary">文件操作</h2>
                </div>

                <!-- 文件上传 -->
                <div class="mb-8 pb-6 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">文件上传</h3>
                    <div class="space-y-4">
                        <div class="form-group">
                            <label class="block text-sm font-medium text-gray-700 mb-1">选择文件</label>
                            <input type="file" id="uploadFile"
                                   class="block w-full text-sm text-gray-500
                                    file:mr-4 file:py-2 file:px-4
                                    file:rounded-lg file:border-0
                                    file:text-sm file:font-medium
                                    file:bg-primary file:text-white
                                    hover:file:bg-primary/90 transition-custom">
                        </div>
                        <div class="form-group">
                            <label for="uploadPath" class="block text-sm font-medium text-gray-700 mb-1">HDFS端路径</label>
                            <input type="text" id="uploadPath" placeholder="请输入上传路径"
                                   class="block w-full rounded-lg border border-gray-300 py-2 px-4 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
                            <p class="text-xs text-gray-500 mt-1">可供上传输入和获取文件列表搜索</p>
                        </div>
                        <button onclick="uploadFile()"
                                class="bg-primary text-white rounded-lg py-2 px-6 font-medium btn-hover-effect transition-custom">
                            上传文件
                        </button>
                    </div>
                </div>

                <!-- 文件列表 -->
                <div class="mb-8 pb-6 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">文件列表</h3>
                    <button onclick="listFiles()"
                            class="bg-primary text-white rounded-lg py-2 px-6 font-medium btn-hover-effect transition-custom mb-4">
                        获取文件列表
                    </button>
                    <div id="fileListOutput" class="bg-gray-50 rounded-lg p-4 max-h-64 overflow-y-auto">
                        <!-- 文件列表将在这里显示 -->
                        <p class="text-gray-500 text-center">请点击"获取文件列表"按钮</p>
                    </div>
                </div>

                <!-- 文件操作按钮 -->
                <div>
                    <h3 class="text-lg font-medium text-gray-700 mb-4">文件管理</h3>
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
                        <button onclick="downloadFile()"
                                class="bg-white text-primary border border-primary rounded-lg py-2 px-4 font-medium hover:bg-primary/5 transition-custom">
                            下载
                        </button>
                        <button onclick="deleteFile()"
                                class="bg-white text-red-600 border border-red-600 rounded-lg py-2 px-4 font-medium hover:bg-red-50 transition-custom">
                            删除
                        </button>
                        <button onclick="renameFile()"
                                class="bg-white text-primary border border-primary rounded-lg py-2 px-4 font-medium hover:bg-primary/5 transition-custom">
                            重命名
                        </button>
                        <button onclick="copyFile()"
                                class="bg-white text-primary border border-primary rounded-lg py-2 px-4 font-medium hover:bg-primary/5 transition-custom">
                            复制
                        </button>
                        <button onclick="moveFile()"
                                class="bg-white text-primary border border-primary rounded-lg py-2 px-4 font-medium hover:bg-primary/5 transition-custom">
                            移动
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="mt-12 text-center text-gray-500 text-sm">
        <p>数据科学2204 第十组</p>
    </footer>
</div>

<!-- 成功提示弹窗 -->
<div id="successToast" class="fixed bottom-6 right-6 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center">
    <span id="toastMessage">操作成功</span>
</div>

<!-- 加载中提示 -->
<div id="loadingOverlay" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white p-6 rounded-lg shadow-xl flex items-center">
        <div class="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-primary mr-4"></div>
        <span id="loadingMessage" class="text-gray-700">处理中...</span>
    </div>
</div>

<script>
    let userId;

    // 显示成功提示
    function showSuccessToast(message) {
        const toast = document.getElementById('successToast');
        const toastMessage = document.getElementById('toastMessage');

        toastMessage.textContent = message;
        toast.classList.remove('translate-y-20', 'opacity-0');
        toast.classList.add('translate-y-0', 'opacity-100');

        setTimeout(() => {
            toast.classList.remove('translate-y-0', 'opacity-100');
            toast.classList.add('translate-y-20', 'opacity-0');
        }, 3000);
    }

    // 显示加载提示
    function showLoading(message = "处理中...") {
        const loadingOverlay = document.getElementById('loadingOverlay');
        const loadingMessage = document.getElementById('loadingMessage');

        loadingMessage.textContent = message;
        loadingOverlay.classList.remove('hidden');
    }

    // 隐藏加载提示
    function hideLoading() {
        const loadingOverlay = document.getElementById('loadingOverlay');
        loadingOverlay.classList.add('hidden');
    }

    // 登录
    document.getElementById('loginForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        if (!username || !password) {
            alert("请输入用户名和密码");
            return;
        }

        showLoading("正在登录...");

        const user = {
            username: username,
            password: password
        };

        $.ajax({
            url: '/user/login',
            type: 'POST',
            data: JSON.stringify(user),
            contentType: 'application/json',
            success: function (data) {
                hideLoading();
                const status = data.status;
                if (status === "登录成功") {
                    userId = data.userId;
                    showSuccessToast(`登录成功，欢迎使用云盘系统，用户${username}`);
                    document.getElementById('loginSection').style.display = 'none';
                    document.getElementById('registerSection').style.display = 'none';
                    document.getElementById('fileOperations').style.display = 'block';
                }
                else if (status === "用户名不存在") {
                    alert("登录的用户名不存在，请检查后重试");
                }
                else {
                    alert(status);
                }
            },
            error: function (error) {
                hideLoading();
                if (error.responseJSON && error.responseJSON.status === "密码错误") {
                    alert("登录密码错误，请重新输入");
                }
                else {
                    alert('登录失败，请检查网络或稍后重试');
                }
            }
        });
    });

    // 注册
    document.getElementById('registerForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const newUsername = document.getElementById('newUsername').value;
        const newPassword = document.getElementById('newPassword').value;

        if (!newUsername || !newPassword) {
            alert("请输入用户名和密码");
            return;
        }

        if (newPassword.length < 6) {
            alert("密码长度至少需要6个字符");
            return;
        }

        showLoading("正在注册...");

        const user = {
            username: newUsername,
            password: newPassword
        };

        $.ajax({
            url: '/user/register',
            type: 'POST',
            data: JSON.stringify(user),
            contentType: 'application/json',
            success: function (data) {
                hideLoading();
                const status = data.status;
                if (status === "注册成功") {
                    showSuccessToast("注册成功，正在登录...");
                    userId = data.userId;
                    document.getElementById('loginSection').style.display = 'none';
                    document.getElementById('registerSection').style.display = 'none';
                    document.getElementById('fileOperations').style.display = 'block';
                } else if (status === "用户名已存在") {
                    alert("注册的用户名已存在，请更换用户名");
                } else {
                    alert(status);
                }
            },
            error: function (error) {
                hideLoading();
                console.error("注册请求失败:", error);
                alert('注册失败，请检查网络或稍后重试');
            }
        });
    });

    // 文件上传
    function uploadFile() {
        if (!userId) {
            alert("请先登录");
            return;
        }
        const file = document.getElementById('uploadFile').files[0];
        if (!file) {
            alert('请选择要上传的文件');
            return;
        }
        const uploadPath = document.getElementById('uploadPath').value;

        showLoading("正在上传文件...");

        const formData = new FormData();
        formData.append('file', file);
        formData.append('userId', userId);
        formData.append('uploadPath', uploadPath);

        $.ajax({
            url: '/file/upload',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function (response) {
                hideLoading();
                try {
                    const data = typeof response === 'string' ? JSON.parse(response) : response;
                    if (data.message && data.message.includes("成功")) {
                        showSuccessToast(data.message);
                        listFiles();
                    } else {
                        alert(data.message || "上传失败");
                    }
                } catch (error) {
                    console.error('解析上传响应失败:', error);
                    alert('上传失败: ' + response);
                }
            },
            error: function (error) {
                hideLoading();
                console.error('上传请求失败:', error);
                if (error.status === 500) {
                    alert('服务器内部错误，上传出现异常');
                } else {
                    alert('文件上传失败，请检查网络或稍后重试');
                }
            }
        });
    }

    // 文件下载
    function downloadFile() {
        if (!userId) {
            alert("请先登录");
            return;
        }
        const uploadPath = document.getElementById('uploadPath').value;
        if (!uploadPath) {
            alert('请输入要下载的文件路径');
            return;
        }

        showLoading("准备下载文件...");

        const requestData = {
            userId: userId,
            uploadPath: uploadPath
        };

        $.ajax({
            url: '/file/download',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(requestData),
            success: function (response) {
                hideLoading();
                try {
                    const data = typeof response === 'string' ? JSON.parse(response) : response;
                    if (data.message && data.message.includes("成功")) {
                        showSuccessToast(data.message);

                        // 创建隐藏表单，通过新的端点获取文件
                        const form = document.createElement('form');
                        form.action = '/file/download/serve';
                        form.method = 'POST';
                        form.style.display = 'none';

                        const userIdInput = document.createElement('input');
                        userIdInput.type = 'hidden';
                        userIdInput.name = 'userId';
                        userIdInput.value = userId;

                        const uploadPathInput = document.createElement('input');
                        uploadPathInput.type = 'hidden';
                        uploadPathInput.name = 'uploadPath';
                        uploadPathInput.value = uploadPath;

                        form.appendChild(userIdInput);
                        form.appendChild(uploadPathInput);

                        document.body.appendChild(form);
                        form.submit();
                        document.body.removeChild(form);
                    } else {
                        alert(data.message || "下载失败");
                    }
                } catch (error) {
                    console.error('解析下载响应失败:', error);
                    alert('下载失败: ' + response);
                }
            },
            error: function (error) {
                hideLoading();
                console.error('下载请求失败:', error);
                alert('文件下载请求失败，请检查网络或稍后重试');
            }
        });
    }

    // 文件删除
    function deleteFile() {
        if (!userId) {
            alert("请先登录");
            return;
        }
        const uploadPath = document.getElementById('uploadPath').value;
        if (!uploadPath) {
            alert('请输入要删除的文件路径');
            return;
        }
        if (!confirm('确定要删除该文件吗?此操作不可撤销!')) {
            return;
        }

        showLoading("正在删除文件...");

        const fileObj = {
            userId: userId,
            uploadPath: uploadPath
        };

        $.ajax({
            url: '/file/delete',
            type: 'POST',
            data: JSON.stringify(fileObj),
            contentType: 'application/json',
            success: function (response) {
                hideLoading();
                try {
                    const data = typeof response === 'string' ? JSON.parse(response) : response;
                    if (data.message && data.message.includes("成功")) {
                        showSuccessToast(data.message);
                        listFiles();
                    } else {
                        alert(data.message || "删除失败");
                    }
                } catch (error) {
                    console.error('解析删除响应失败:', error);
                    alert('删除失败: ' + response);
                }
            },
            error: function (error) {
                hideLoading();
                console.error('删除请求失败:', error);
                alert('文件删除失败，请检查网络或稍后重试');
            }
        });
    }

    // 文件重命名
    function renameFile() {
        if (!userId) {
            alert("请先登录");
            return;
        }
        const uploadPath = document.getElementById('uploadPath').value;
        if (!uploadPath) {
            alert('请输入要重命名的文件路径');
            return;
        }

        // 从路径中提取当前文件名
        const pathParts = uploadPath.split('/');
        const currentFileName = pathParts.pop();
        const fileDir = pathParts.join('/');

        const newName = prompt("请输入新文件名", currentFileName);
        if (!newName || newName === currentFileName) {
            return;
        }

        showLoading("正在重命名文件...");

        const data = {
            userId: userId,
            uploadPath: uploadPath,
            newFileName: newName
        };

        $.ajax({
            url: '/file/rename',
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function (response) {
                hideLoading();
                try {
                    const data = typeof response === 'string' ? JSON.parse(response) : response;
                    if (data.message && data.message.includes("成功")) {
                        showSuccessToast(data.message);
                        document.getElementById('uploadPath').value = fileDir ? `${fileDir}/${newName}` : newName;
                        listFiles();
                    } else {
                        alert(data.message || "重命名失败");
                    }
                } catch (error) {
                    console.error('解析重命名响应失败:', error);
                    alert('重命名失败: ' + response);
                }
            },
            error: function (error) {
                hideLoading();
                console.error('重命名请求失败:', error);
                alert('文件重命名失败，请检查网络或稍后重试');
            }
        });
    }

    // 文件复制
    function copyFile() {
        if (!userId) {
            alert("请先登录");
            return;
        }
        const uploadPath = document.getElementById('uploadPath').value;
        if (!uploadPath) {
            alert('请输入要复制的源文件路径');
            return;
        }

        // 从路径中提取当前文件名
        const pathParts = uploadPath.split('/');
        const currentFileName = pathParts.pop();

        // 处理HDFS路径前缀
        let basePath = uploadPath.startsWith('hdfs://')
            ? uploadPath.substring(12) // 移除'hdfs://mycluster'前缀
            : uploadPath;

        // 提取目录部分
        const fileDir = basePath.substring(0, basePath.lastIndexOf('/'));
        const defaultTargetDir = fileDir.startsWith('/') ? fileDir : '/' + fileDir;

        // 提示输入目标目录，默认为当前目录
        const targetDir = prompt("请输入目标目录", defaultTargetDir);
        if (!targetDir) {
            return;
        }

        // 构建完整的目标路径
        let targetPath = targetDir;
        if (!targetDir.endsWith('/')) {
            targetPath += '/';
        }
        targetPath += currentFileName;

        // 添加HDFS前缀
        if (!targetPath.startsWith('hdfs://')) {
            targetPath = 'hdfs://mycluster' + targetPath;
        }

        if (!confirm('确定要复制该文件到以下位置吗?\n' + targetPath)) {
            return;
        }

        showLoading("正在复制文件...");

        const data = {
            sourceUserId: userId,
            sourceUploadPath: uploadPath,
            targetUserId: userId,
            targetUploadPath: targetPath
        };

        console.log("复制请求数据:", data); // 调试信息

        $.ajax({
            url: '/file/copy',
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function (response) {
                hideLoading();
                try {
                    const data = typeof response === 'string' ? JSON.parse(response) : response;
                    if (data.message && data.message.includes("成功")) {
                        showSuccessToast(data.message);
                        listFiles();
                    } else {
                        alert(data.message || "复制失败");
                    }
                } catch (error) {
                    console.error('解析复制响应失败:', error);
                    alert('复制失败: 无法解析服务器响应');
                }
            },
            error: function (error) {
                hideLoading();
                console.error('复制请求失败:', error);
                alert('文件复制请求失败，请检查网络或稍后重试');
            }
        });
    }

    // 文件移动
    function moveFile() {
        if (!userId) {
            alert("请先登录");
            return;
        }
        const uploadPath = document.getElementById('uploadPath').value;
        if (!uploadPath) {
            alert('请输入要移动的源文件路径');
            return;
        }

        // 从路径中提取当前文件名
        const pathParts = uploadPath.split('/');
        const currentFileName = pathParts.pop();

        // 处理HDFS路径前缀
        let basePath = uploadPath.startsWith('hdfs://')
            ? uploadPath.substring(12) // 移除'hdfs://mycluster'前缀
            : uploadPath;

        // 提取目录部分
        const fileDir = basePath.substring(0, basePath.lastIndexOf('/'));
        const defaultTargetDir = fileDir.startsWith('/') ? fileDir : '/' + fileDir;

        // 提示输入目标目录，默认为当前目录
        const targetDir = prompt("请输入目标目录", defaultTargetDir);
        if (!targetDir) {
            return;
        }

        // 构建完整的目标路径
        let targetPath = targetDir;
        if (!targetDir.endsWith('/')) {
            targetPath += '/';
        }
        targetPath += currentFileName;

        // 添加HDFS前缀
        if (!targetPath.startsWith('hdfs://')) {
            targetPath = 'hdfs://mycluster' + targetPath;
        }

        if (!confirm('确定要移动该文件到以下位置吗?\n' + targetPath)) {
            return;
        }

        showLoading("正在移动文件...");

        const data = {
            sourceUserId: userId,
            sourceUploadPath: uploadPath,
            targetUserId: userId,
            targetUploadPath: targetPath
        };

        console.log("移动请求数据:", data); // 调试信息

        $.ajax({
            url: '/file/move',
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function (response) {
                hideLoading();
                try {
                    const data = typeof response === 'string' ? JSON.parse(response) : response;
                    if (data.message && data.message.includes("成功")) {
                        showSuccessToast(data.message);
                        document.getElementById('uploadPath').value = targetPath;
                        listFiles();
                    } else {
                        alert(data.message || "移动失败");
                    }
                } catch (error) {
                    console.error('解析移动响应失败:', error);
                    alert('移动失败: ' + response);
                }
            },
            error: function (error) {
                hideLoading();
                console.error('移动请求失败:', error);

                // 更详细的错误提示
                if (error.responseJSON && error.responseJSON.message) {
                    alert('文件移动失败: ' + error.responseJSON.message);
                } else {
                    alert('文件移动失败，请检查网络或稍后重试');
                }
            }
        });
    }

    // 显示文件列表
    function listFiles() {
        if (!userId) {
            alert("请先登录");
            return;
        }

        showLoading("正在获取文件列表...");

        const uploadPath = document.getElementById('uploadPath').value;
        const queryParams = "?userId=" + userId + "&path=" + encodeURIComponent(uploadPath);
        const url = `/file/list/${userId}${queryParams}`;

        $.ajax({
            url: url,
            type: 'GET',
            success: function (response) {
                hideLoading();
                try {
                    const fileListOutput = document.getElementById('fileListOutput');
                    fileListOutput.innerHTML = '';

                    if (!response || response.length === 0) {
                        fileListOutput.innerHTML = '<p class="text-gray-500 text-center">没有找到文件</p>';
                        return;
                    }

                    response.forEach(function (file) {
                        const fileItem = document.createElement('div');
                        fileItem.className = 'p-3 border-b border-gray-200 last:border-0 hover:bg-gray-100 transition-custom cursor-pointer';
                        fileItem.onclick = function() {
                            document.getElementById('uploadPath').value = file.filePath;
                        };

                        const fileName = document.createElement('div');
                        fileName.className = 'font-medium text-gray-800 mb-1';
                        fileName.textContent = file.fileName;

                        const fileDetails = document.createElement('div');
                        fileDetails.className = 'text-sm text-gray-500 flex flex-wrap gap-3';

                        const fileSize = document.createElement('span');
                        fileSize.textContent = formatFileSize(file.fileSize);

                        const filePath = document.createElement('span');
                        filePath.textContent = file.filePath;

                        fileDetails.appendChild(fileSize);
                        fileDetails.appendChild(filePath);

                        fileItem.appendChild(fileName);
                        fileItem.appendChild(fileDetails);

                        fileListOutput.appendChild(fileItem);
                    });
                } catch (error) {
                    console.error('解析文件列表响应失败: ', error);
                    alert('解析文件列表响应失败: ' + error.message);
                }
            },
            error: function (error) {
                hideLoading();
                console.error('获取文件列表失败:', error);
                alert('文件列表获取失败，请检查网络或稍后重试');
            }
        });
    }

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';

        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));

        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 初始化页面
    $(document).ready(function () {
        // 添加键盘事件处理
        document.getElementById('uploadPath').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                listFiles();
            }
        });
    });
</script>
</body>
</html>